﻿using Microsoft.Extensions.Primitives;
using System.Globalization;
using Volo.Abp.Localization;

namespace CTP.CRM.Core.Localization
{
    public class RequestCultureMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestCultureMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                StringValues? language = context.Request?.Headers["Accept-Language"];
                StringValues? stringValues = language;
                object culture;
                if (!string.IsNullOrEmpty(stringValues.HasValue ? ((string?)stringValues.GetValueOrDefault()) : null))
                {
                    stringValues = language;
                    culture = (stringValues.HasValue ? ((string?)stringValues.GetValueOrDefault()) : null);
                }
                else
                {
                    culture = "zh";
                }

                CultureHelper.Use((string)culture);
            }
            catch (Exception ex) when (ex is CultureNotFoundException)
            {
                CultureHelper.Use("zh");
            }
            finally
            {
                await _next(context);
            }
        }
    }
}
